/**
 * Created by zxr on 16/11/11.
 */
var http = require('http');
var url = require('url');
var fs = require('fs');
var qs = require('querystring');
var formidable = require('formidable');
//var events = require('events').EventEmitter;
//var channel = new events();




var items = [];
var percent = 0;
var server = http.createServer(function (req, res) {
	if (req.url == '/') {
		switch (req.method) {
			case 'POST':
				upload(req,res);
				break;
			case 'GET':
				show(res);
				break;
			default :
				badRequest(res);
		}
	} else if (req.url = '/upload'){
		var s = percent.toString();
		res.statusCode = 200;
		res.setHeader('Content-Type','text/json');
		res.addTrailers({'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667'});
		res.write(s);
		res.end();
	}else {
		notFind(res);
	}
});
var io = require('socket.io')(server);
//
//io.on('connect', function (socket) {
//	socket.emit('news', { hello: 'world' });
//	socket.on('my other event', function (data) {
//		console.log(data);
//	});
//	socket.on('upload',function(){
//		socket.emit('precent',{progress:percent})
//	})
//});




function show(res) {
	var stream = fs.createReadStream('./upload/upload.html');
	stream.pipe(res);

}
function badRequest( res) {
	res.statusCode = 400;
	res.setHeader('Content-Type','text/plain');
	res.end('Bad Request');
}
function notFind(res) {
	res.statusCode = 404;
	res.setHeader('Content-Type','text/plain');
	res.end('Not Find');
}
// 检查Post文件的类型
function isFormData(req){
	var type = req.headers['content-type'] || '';
	return 0 == type.indexOf('multipart/form-data');
}
 function upload(req,res){
	 if (!isFormData(req)){
		 res.statusCode = 400;
		 res.end('Bad Request: expecting multipart/form-data');
		 return false;
	 }
	 var form = new formidable();
	 form.uploadDir = './upload_file';
	 form.parse(req,function(err, fields, files) {
		 console.log(fields)
		 console.log(files)
		 //res.writeHead(200, {'content-type': 'text/plain'});
		 //res.write('received upload:\n\n');
		 //res.end(util.inspect({fields: fields, files: files}));
	 });
	 form.on('progress',function(byteReceived,byteExpected){
		  percent = Math.floor(  byteReceived/byteExpected*100 );
		  io.sockets.emit('precent',percent);
		 if (percent == 100){
			 res.end('上传完成');
		 }

	 })
 }


server.listen('8000');